'use client';

import { useState, useEffect, useMemo } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

interface Car {
  id: number;
  title: string;
  vin: string;
  carType: number;
  brand: string;
  price: number;
  type: 'sedan' | 'suv' | 'coupe' | 'hatchback';
  fuelType: 'gasoline' | 'electric' | 'hybrid' | 'diesel';
  year: number;
  status: 'active' | 'sold' | 'reserved';
  condition: 'new' | 'used';
  mileage?: number;
  location: string;
  createdAt: string;
}

export default function CarsPage() {
  const { user } = useAuth();
  const router = useRouter();
  const [cars, setCars] = useState<Car[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterBrand, setFilterBrand] = useState<string>('all');
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [isExporting, setIsExporting] = useState(false);

  // 扩展的模拟汽车数据
  const mockCars: Car[] = [
    {
      id: 1,
      title: 'Model S',
      vin: 'LCGSIIi66448484848',
      brand: '特斯拉',
      carType:1,
      mileage:200,
      price: 850000,
      type: 'sedan',
      fuelType: 'electric',
      year: 2024,
      status: 'active',
      condition: 'new',
      location: '北京',
      createdAt: '2024-01-15'
    },
    {
      id: 2,
      title: 'E-Class',
      vin: 'LCGSIIi66448484848',
      brand: '奔驰',
      price: 520000,
           carType:1,
      mileage:200,
      type: 'sedan',
      fuelType: 'gasoline',
      year: 2024,
      status: 'active',
      condition: 'new',
      location: '上海',
      createdAt: '2024-01-16'
    },
    {
      id: 3,
      title: '3 Series',
      vin: 'LCGSIIi66448484848',
      brand: '宝马',
       carType:1,
      price: 380000,
      type: 'sedan',
      fuelType: 'gasoline',
      year: 2022,
      status: 'sold',
      condition: 'used',
      mileage: 15000,
      location: '广州',
      createdAt: '2024-01-17'
    },
    {
      id: 4,
      title: 'Model 3',
      vin: 'LCGSIIi66448484848',
      brand: '特斯拉',
      price: 280000,
      type: 'sedan',
       carType:1,
      fuelType: 'electric',
      year: 2024,
      status: 'reserved',
      condition: 'new',
      location: '深圳',
      createdAt: '2024-01-18'
    },
    {
      id: 5,
      title: 'X5',
      vin: 'LCGSIIi66448484848',
      brand: '宝马',
      price: 680000,
       carType:1,
      type: 'suv',
      fuelType: 'gasoline',
      year: 2023,
      status: 'active',
      condition: 'new',
      location: '北京',
      createdAt: '2024-01-19'
    },
    {
      id: 6,
      title: 'A4',
      brand: '奥迪',
      price: 320000,
      vin: 'LCGSIIi66448484848',
       carType:1,
      type: 'sedan',
      fuelType: 'gasoline',
      year: 2023,
      status: 'active',
      condition: 'new',
      location: '成都',
      createdAt: '2024-01-20'
    }
  ];

  useEffect(() => {
    // if (!user || user.role !== 'admin') {
    //   router.push('/login');
    //   return;
    // }

    setTimeout(() => {
      setCars(mockCars);
      setIsLoading(false);
    }, 1000);
  }, [user, router]);

  const handleDeleteCar = (carId: number) => {
    if (confirm('确定要删除这辆车吗？')) {
      setCars(cars.filter(car => car.id !== carId));
    }
  };

  const handleStatusChange = (carId: number, newStatus: 'active' | 'sold' | 'reserved') => {
    setCars(cars.map(car =>
      car.id === carId ? { ...car, status: newStatus } : car
    ));
  };

  // 导出CSV功能
  const exportToCSV = () => {
    setIsExporting(true);

    const headers = ['ID', '车辆名称', '品牌', '价格', '车型', '燃料类型', '年份', '状态', '车况', '里程', '位置', '创建时间'];
    const csvData = filteredAndSearchedCars.map(car => [
      car.id,
      car.title,
      car.brand,
      car.price,
      car.type === 'sedan' ? '轿车' : car.type === 'suv' ? 'SUV' : car.type === 'coupe' ? '跑车' : '掀背车',
      car.fuelType === 'gasoline' ? '汽油' : car.fuelType === 'electric' ? '电动' : car.fuelType === 'hybrid' ? '混动' : '柴油',
      car.year,
      car.status === 'active' ? '在售' : car.status === 'sold' ? '已售' : '预订',
      car.condition === 'new' ? '新车' : '二手车',
      car.mileage || 0,
      car.location,
      car.createdAt
    ]);

    const csvContent = [headers, ...csvData]
      .map(row => row.map(field => `"${field}"`).join(','))
      .join('\n');

    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `汽车列表_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    setTimeout(() => setIsExporting(false), 1000);
  };

  // 过滤和搜索汽车
  const filteredAndSearchedCars = useMemo(() => {
    return cars.filter(car => {
      // 状态过滤
      if (filterStatus !== 'all' && car.status !== filterStatus) return false;
      // 品牌过滤
      if (filterBrand !== 'all' && car.brand !== filterBrand) return false;
      // 搜索过滤
      if (searchTerm) {
        const searchLower = searchTerm.toLowerCase();
        return (
          car.title.toLowerCase().includes(searchLower) ||
          car.brand.toLowerCase().includes(searchLower) ||
          car.location.toLowerCase().includes(searchLower) 
          // ||car.id.toLowerCase().includes(searchLower)
        );
      }
      return true;
    });
  }, [cars, filterStatus, filterBrand, searchTerm]);

  // 分页数据
  const paginatedCars = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    return filteredAndSearchedCars.slice(startIndex, startIndex + pageSize);
  }, [filteredAndSearchedCars, currentPage, pageSize]);

  // 总页数
  const totalPages = Math.ceil(filteredAndSearchedCars.length / pageSize);

  // 获取品牌列表
  const brands = Array.from(new Set(cars.map(car => car.brand)));

  // 重置分页当搜索或过滤条件改变时
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, filterStatus, filterBrand]);

  if (!user || user.role !== 'admin') {
    return null;
  }

  return (
    <>
      {/* Header */}
      <div className="mb-8">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">汽车管理</h1>
            <p className="text-gray-600">管理汽车库存和信息</p>
          </div>
          <div className="flex space-x-4">
            <button
              onClick={exportToCSV}
              disabled={isExporting || filteredAndSearchedCars.length === 0}
              className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
            >
              {isExporting ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  <span>导出中...</span>
                </>
              ) : (
                <>
                  <span>📊</span>
                  <span>导出CSV</span>
                </>
              )}
            </button>
            <Link
              href="/admin/cars/new"
              className="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700"
            >
              添加汽车
            </Link>
          </div>
        </div>
      </div>
      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-6 mb-8">
        <div className="bg-blue-50 rounded-lg shadow-sm p-6 border border-blue-100">
          <div className="text-2xl font-bold text-blue-600">{cars.length}</div>
          <div className="text-gray-600">总车辆数</div>
        </div>
        <div className="bg-green-50 rounded-lg shadow-sm p-6 border border-green-100">
          <div className="text-2xl font-bold text-green-600">
            {cars.filter(car => car.status === 'active').length}
          </div>
          <div className="text-gray-600">新车车辆</div>
        </div>
        <div className="bg-yellow-50 rounded-lg shadow-sm p-6 border border-yellow-100">
          <div className="text-2xl font-bold text-yellow-600">
            {cars.filter(car => car.status === 'reserved').length}
          </div>
          <div className="text-gray-600">二手车辆</div>
        </div>
      </div>

      {/* Search and Filters */}
      <div className="mb-6 space-y-4">
        {/* Search Bar */}
        <div className="flex items-center space-x-4">
          <div className="flex-1 relative">
            <input
              type="text"
              placeholder="搜索车辆名称、品牌、位置或ID..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-4 py-2 pl-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <span className="text-gray-400">🔍</span>
            </div>
            {searchTerm && (
              <button
                onClick={() => setSearchTerm('')}
                className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600"
              >
                ✕
              </button>
            )}
          </div>
        </div>

        {/* Filters */}
        <div className="flex flex-wrap gap-4">
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">所有状态</option>
            <option value="active">在售</option>
            <option value="sold">已售</option>
            <option value="reserved">预订</option>
          </select>
          <select
            value={filterBrand}
            onChange={(e) => setFilterBrand(e.target.value)}
            className="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">所有品牌</option>
            {brands.map(brand => (
              <option key={brand} value={brand}>{brand}</option>
            ))}
          </select>
          <select
            value={pageSize}
            onChange={(e) => {
              setPageSize(Number(e.target.value));
              setCurrentPage(1);
            }}
            className="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value={5}>每页 5 条</option>
            <option value={10}>每页 10 条</option>
            <option value={20}>每页 20 条</option>
            <option value={50}>每页 50 条</option>
          </select>
        </div>

        {/* Results Info */}
        <div className="flex justify-between items-center text-sm text-gray-600">
          <div>
            显示 {filteredAndSearchedCars.length > 0 ? (currentPage - 1) * pageSize + 1 : 0} - {Math.min(currentPage * pageSize, filteredAndSearchedCars.length)} 条，
            共 {filteredAndSearchedCars.length} 条记录
            {searchTerm && (
              <span className="ml-2 text-blue-600">
                (搜索: "{searchTerm}")
              </span>
            )}
          </div>
          {(filterStatus !== 'all' || filterBrand !== 'all' || searchTerm) && (
            <button
              onClick={() => {
                setFilterStatus('all');
                setFilterBrand('all');
                setSearchTerm('');
                setCurrentPage(1);
              }}
              className="text-blue-600 hover:text-blue-800"
            >
              清除所有筛选
            </button>
          )}
        </div>
      </div>



      {/* Cars Table */}
      <div className="bg-white rounded-lg shadow-sm overflow-hidden border">
        <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
          <h2 className="text-xl font-semibold text-gray-900">
            车辆列表
          </h2>
        </div>

        {isLoading ? (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">加载中...</p>
          </div>
        ) : filteredAndSearchedCars.length === 0 ? (
          <div className="p-8 text-center">
            <div className="text-gray-400 text-6xl mb-4">🚗</div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">没有找到车辆</h3>
            <p className="text-gray-500 mb-4">
              {searchTerm || filterStatus !== 'all' || filterBrand !== 'all'
                ? '请尝试调整搜索条件或筛选器'
                : '还没有添加任何车辆'}
            </p>
            {(searchTerm || filterStatus !== 'all' || filterBrand !== 'all') && (
              <button
                onClick={() => {
                  setSearchTerm('');
                  setFilterStatus('all');
                  setFilterBrand('all');
                }}
                className="text-blue-600 hover:text-blue-800"
              >
                清除筛选条件
              </button>
            )}
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      编号
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      车辆信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      vin
                    </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      类型
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      价格
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      排量/续航
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      位置
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {paginatedCars.map((car) => (
                    <tr key={car.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {car.id}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {car.title}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-500">
                          {car.vin}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-500">
                           {car.carType === 1 ? '新车' : '二手车'}
                        
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ¥{car.price.toLocaleString()}
                      </td>
                       <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                         {car.mileage && ` · ${car.mileage.toLocaleString()}km`}
                      </td>
                      
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm text-gray-900">
                          {car.type === 'sedan' ? '轿车' : car.type === 'suv' ? 'SUV' : car.type === 'coupe' ? '跑车' : '掀背车'}
                        </div>
                        <div className="text-sm text-gray-500">
                          {car.fuelType === 'gasoline' ? '汽油' : car.fuelType === 'electric' ? '电动' : car.fuelType === 'hybrid' ? '混动' : '柴油'}
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <select
                          value={car.status}
                          onChange={(e) => handleStatusChange(car.id, e.target.value as 'active' | 'sold' | 'reserved')}
                          className={`text-sm border-0 focus:ring-0 focus:outline-none appearance-none ${car.status === 'active'
                              ? 'text-green-600 bg-green-50'
                              : car.status === 'sold'
                                ? 'text-red-600 bg-red-50'
                                : 'text-yellow-600 bg-yellow-50'
                            } rounded px-2 py-1`}
                        >
                          <option value="active">在售</option>
                          <option value="sold">已售</option>
                          <option value="reserved">预订</option>
                        </select>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {car.location}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <div className="flex space-x-2">
                          <Link
                            href={`/cars/${car.id}`}
                            className="text-blue-600 hover:text-blue-900"
                          >
                            查看
                          </Link>
                          <Link
                            href={`/admin/cars/${car.id}/edit`}
                            className="text-green-600 hover:text-green-900"
                          >
                            编辑
                          </Link>
                          <button
                            onClick={() => handleDeleteCar(car.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            删除
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="px-6 py-4 border-t border-gray-200 bg-gray-50">
                <div className="flex items-center justify-between">
                  <div className="text-sm text-gray-700">
                    第 {currentPage} 页，共 {totalPages} 页
                  </div>
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => setCurrentPage(1)}
                      disabled={currentPage === 1}
                      className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      首页
                    </button>
                    <button
                      onClick={() => setCurrentPage(currentPage - 1)}
                      disabled={currentPage === 1}
                      className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      上一页
                    </button>

                    {/* Page Numbers */}
                    <div className="flex space-x-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum;
                        if (totalPages <= 5) {
                          pageNum = i + 1;
                        } else if (currentPage <= 3) {
                          pageNum = i + 1;
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i;
                        } else {
                          pageNum = currentPage - 2 + i;
                        }

                        return (
                          <button
                            key={pageNum}
                            onClick={() => setCurrentPage(pageNum)}
                            className={`px-3 py-1 text-sm border rounded ${currentPage === pageNum
                                ? 'bg-blue-600 text-white border-blue-600'
                                : 'border-gray-300 hover:bg-gray-100'
                              }`}
                          >
                            {pageNum}
                          </button>
                        );
                      })}
                    </div>

                    <button
                      onClick={() => setCurrentPage(currentPage + 1)}
                      disabled={currentPage === totalPages}
                      className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      下一页
                    </button>
                    <button
                      onClick={() => setCurrentPage(totalPages)}
                      disabled={currentPage === totalPages}
                      className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      末页
                    </button>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}